package com.hzhq.contract.util;

import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import org.bson.BSONObject;
import org.bson.Document;
import org.bson.types.ObjectId;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author hzhq
 * @create 2021/4/8 4:11 下午
 * @email hzhq1255@163.com
 */
public class ConvertUtil {


    public static <T> List<T> objToList(Object obj, Class<T> clazz){
       List<T> result = new ArrayList<T>();
       if(obj instanceof List<?>){
           for(Object o: (List<?>) obj){
               result.add(clazz.cast(o));
           }
       }
       return result;
    }



    public static <T> T objToBean(Object obj, Class<T> clazz){
        if (obj == null){
            return null;
        }
        return clazz.cast(obj);
    }

    public static ObjectId stringToObjectId(String id){
        try{
            return new ObjectId(id);
        } catch (Exception e){
            return null;
        }
    }

    public static String objectIdToString(ObjectId id){
        if(null == id){
            return null;
        }
        return id.toString();
    }

    public static Date stringToDate(String dateString){
        try {
            SimpleDateFormat  formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return formatter.parse(dateString);
        }catch (ParseException e){
            e.printStackTrace();
        }
        return null;
    }

    public static JSONObject map2Json(Map<String, Object> map) {
        return new JSONObject(map);
    }

    public static Map<String, Object> json2Map(JSONObject jsonObject) {
        return jsonObject;
    }

    public static String json2String(JSONObject jsonObject) {
        return jsonObject.toJSONString();
    }

    public static JSONObject string2Json(String json) throws ParseException {
        return JSONObject.parseObject(json);
    }

    public static DBObject json2Bson(JSONObject jsonObject){
        return (DBObject) jsonObject;
    }

    public static DBObject json2Bson(String json){
        return (DBObject) JSONObject.parseObject(json);
    }

    public static DBObject map2Bson(Map<String,Object> map){
        return new BasicDBObject(map);
    }

    public static Document json2Document(JSONObject jsonObject) throws ParseException {
        return Document.parse(jsonObject.toJSONString());
    }

    public static Document json2Document(String json) throws ParseException{
        return Document.parse(json);
    }

    public static Document map2Document(Map<String,Object> map){
        return new Document(map);
    }


}
